﻿using System;
using System.Linq;
using AnalysisTool.Core.Common.Extensions.Unity.LogCreationExtension;
using MassPokerTool.Infrastructure.Core.Unity.BuildTrackingExtension;
using MassPokerTool.Infrastructure.Logging;
using Microsoft.Practices.ObjectBuilder2;

namespace MassPokerTool.Infrastructure.Core.Unity.LogCreationExtension
{
    /// <summary>
    /// 
    /// </summary>
    public class LogCreationStrategy : BuilderStrategy
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void PreBuildUp(IBuilderContext context)
        {
            Type typeToBuild = context.BuildKey.Type;
            if (typeof(ILogger).Equals(typeToBuild))
            {

                if (context.Policies.Get<IBuildPlanPolicy>(context.BuildKey) == null)
                {
                    Type typeForLog = GetLogType(context);
                    if (typeForLog.IsGenericType)
                        typeForLog = typeForLog.GetGenericTypeDefinition();
                    IBuildPlanPolicy policy = new LogBuildPlanPolicy(typeForLog);
                    context.Policies.Set<IBuildPlanPolicy>(policy, context.BuildKey);

                    IsPolicySet = true;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void PostBuildUp(IBuilderContext context)
        {
            if (IsPolicySet)
            {
                context.Policies.Clear<IBuildPlanPolicy>(context.BuildKey);
                IsPolicySet = false;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private static Type GetLogType(IBuilderContext context)
        {
            Type logType = typeof(ILogger);

            IBuildTrackingPolicy buildTrackingPolicy = BuildTracking.GetPolicy(context);
            if ((buildTrackingPolicy != null) && (buildTrackingPolicy.BuildKeys.Count >= 2))
            {
                logType = ((NamedTypeBuildKey)buildTrackingPolicy.BuildKeys.ElementAt(1)).Type;
            }
            return logType;
        }

        /// <summary>
        /// 
        /// </summary>
        public bool IsPolicySet { get; private set; }
    }
}
